package com.nx.biz.shopify.service;

import cn.hutool.core.collection.ListUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.nx.biz.shopify.api.bo.ShopifyFulfillment;
import com.nx.biz.shopify.api.bo.ShopifyFulfillmentEvent;
import com.nx.biz.shopify.api.bo.ShopifyOrder;
import com.nx.biz.shopify.api.dto.ShopifyOrderBizDto;
import com.nx.biz.shopify.api.dto.ShopifyOrderVoItem;
import com.nx.biz.shopify.api.qry.OrderSyncListQry;
import com.nx.biz.shopify.mapper.ShopifyFulfillmentMapper;
import com.nx.biz.shopify.model.ShopifyFulfillmentDo;
import com.nx.biz.shopify.model.ShopifyOrderDo;
import com.nx.biz.shopify.model.predicate.ShopifyFulfillmentEventPredicate;
import com.nx.biz.shopify.model.predicate.ShopifyFulfillmentPredicate;
import com.nx.biz.shopify.repo.ShopifyFulfillmentEventRepository;
import com.nx.biz.shopify.repo.ShopifyFulfillmentRepository;
import com.nx.biz.shopify.repo.ShopifyOrderRepository;
import com.nx.common.exception.BusinessException;
import com.nx.common.tools.CheckTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ShopifyBizService {

    @Resource
    private ShopifyFulfillmentMapper shopifyFulfillmentMapper;

    @Resource
    private ShopifyOrderRepository shopifyOrderRepository;
    @Resource
    private ShopifyFulfillmentRepository shopifyFulfillmentRepository;
    @Resource
    private ShopifyFulfillmentEventRepository shopifyFulfillmentEventRepository;

    public ShopifyOrderBizDto queryOrderBizInfo(String shopifyOrderId) {
        // 查询订单
        ShopifyOrder shopifyOrder = shopifyOrderRepository.queryById(shopifyOrderId);
        if (CheckTools.isNullOrEmpty(shopifyOrder)) {
            throw new BusinessException("订单不存在");
        }
        // 转为bizDto结构
        ShopifyOrderBizDto shopifyOrderBizDto = new ShopifyOrderBizDto();
        shopifyOrderBizDto.setId(shopifyOrderId);
        shopifyOrderBizDto.setTrackCompany("");
        shopifyOrderBizDto.setTrackCompanyUrl("");
        shopifyOrderBizDto.setTrackNumber(shopifyOrder.getTrackNumber());
        shopifyOrderBizDto.setZhuandanhao("");

        // 查询运单
        ShopifyFulfillmentPredicate shopifyFulfillmentPredicate = new ShopifyFulfillmentPredicate();
        shopifyFulfillmentPredicate.setEqOrderId(shopifyOrderId);
        List<ShopifyFulfillment> shopifyFulfillmentList = shopifyFulfillmentRepository.queryList(shopifyFulfillmentPredicate);
        if (CheckTools.isNullOrEmpty(shopifyFulfillmentList)) {
            return shopifyOrderBizDto;
        }
        ShopifyFulfillment shopifyFulfillment = shopifyFulfillmentList.get(0);
        shopifyOrderBizDto.setTrackCompany(shopifyFulfillment.getTrackingCompany());
        shopifyOrderBizDto.setTrackCompanyUrl(shopifyFulfillment.getTrackingUrl());
        shopifyOrderBizDto.setTrackNumber(shopifyOrder.getTrackNumber());
        shopifyOrderBizDto.setZhuandanhao(shopifyFulfillment.getTransferNo());

        // 查询运踪
        ShopifyFulfillmentEventPredicate shopifyFulfillmentEventPredicate = new ShopifyFulfillmentEventPredicate();
        shopifyFulfillmentEventPredicate.setEqFulfillmentId(shopifyFulfillment.getId());
        List<ShopifyFulfillmentEvent> fulfillmentEventList = shopifyFulfillmentEventRepository.queryList(shopifyFulfillmentEventPredicate);
        // 转为目标结构
        List<ShopifyOrderBizDto.TrackEvent> trackEventList = fulfillmentEventList.stream().map(item -> {
            ShopifyOrderBizDto.TrackEvent trackEventItem = new ShopifyOrderBizDto.TrackEvent();
            trackEventItem.setId(item.getId());
            trackEventItem.setStatus(item.getStatus());
            trackEventItem.setMessage(item.getMessage());
            trackEventItem.setEventTime(item.getHappenedAt());
            return trackEventItem;
        }).collect(Collectors.toList());
        if (CheckTools.isNotNullOrEmpty(trackEventList)) {
            trackEventList.sort(Comparator.comparing(ShopifyOrderBizDto.TrackEvent::getEventTime));
            ListUtil.reverse(trackEventList);
            shopifyOrderBizDto.setTrackEvents(trackEventList);
        }
        return shopifyOrderBizDto;
    }

    public List<ShopifyOrderVoItem> queryOrderSyncList(OrderSyncListQry syncListQry) {
        String syncStatus = syncListQry.getSyncStatus();

        MPJLambdaWrapper<ShopifyFulfillmentDo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .select(ShopifyFulfillmentDo::getId)
                .select(ShopifyFulfillmentDo::getOrderId)
                .select(ShopifyFulfillmentDo::getStatus)
                .select(ShopifyFulfillmentDo::getShopDomain)
                .select(ShopifyFulfillmentDo::getShipmentStatus)
                .select(ShopifyFulfillmentDo::getService)
                .select(ShopifyFulfillmentDo::getLocationId)
                .select(ShopifyFulfillmentDo::getTrackingCompany)
                .select(ShopifyFulfillmentDo::getTrackingNumber)
                .select(ShopifyFulfillmentDo::getTrackingUrl)
                .select(ShopifyFulfillmentDo::getDestination)
                .select(ShopifyFulfillmentDo::getSyncFlag)
                .select(ShopifyFulfillmentDo::getTransferNo)
                .leftJoin(ShopifyOrderDo.class, ShopifyOrderDo::getId, ShopifyFulfillmentDo::getOrderId);

        if (Objects.equals(syncStatus, "1")) {
            queryWrapper.eq(ShopifyFulfillmentDo::getSyncFlag, 1);
        } else if (Objects.equals(syncStatus, "0")) {
            queryWrapper.eq(ShopifyFulfillmentDo::getSyncFlag, 0);
        }

        if (CheckTools.isNullOrEmpty(syncListQry.getShopDomain())) {
            // 不传shop，一条都不查询
            queryWrapper.eq(ShopifyFulfillmentDo::getShopDomain, "###");
        } else {
            queryWrapper.eq(ShopifyFulfillmentDo::getShopDomain, syncListQry.getShopDomain());
        }

        List<ShopifyFulfillmentDo> shopifyFulfillmentDos = shopifyFulfillmentMapper.selectList(queryWrapper);

        // 转为目标结构
        List<ShopifyOrderVoItem> shopifyOrderVoItemList = shopifyFulfillmentDos.stream().map(item -> {
            ShopifyOrderVoItem shopifyOrderVoItem = new ShopifyOrderVoItem();
            shopifyOrderVoItem.setId(item.getOrderId());
            shopifyOrderVoItem.setFulfillmentId(item.getId());
            shopifyOrderVoItem.setTrackCompany(item.getTrackingCompany());
            shopifyOrderVoItem.setTrackCompanyUrl(item.getTrackingUrl());
            shopifyOrderVoItem.setTrackNumber(item.getTrackingNumber());
            shopifyOrderVoItem.setTransferNo(item.getTransferNo());
            shopifyOrderVoItem.setSyncStatus(String.valueOf(item.getSyncFlag()));
            return shopifyOrderVoItem;
        }).collect(Collectors.toList());

        // merge运踪信息
        for (ShopifyOrderVoItem shopifyOrderVoItem : shopifyOrderVoItemList) {
            ShopifyFulfillmentEventPredicate shopifyFulfillmentEventPredicate = new ShopifyFulfillmentEventPredicate();
            shopifyFulfillmentEventPredicate.setEqFulfillmentId(shopifyOrderVoItem.getFulfillmentId());
            List<ShopifyFulfillmentEvent> fulfillmentEventList = shopifyFulfillmentEventRepository.queryList(shopifyFulfillmentEventPredicate);
            if (CheckTools.isNotNullOrEmpty(fulfillmentEventList)) {
                fulfillmentEventList.sort(Comparator.comparing(ShopifyFulfillmentEvent::getHappenedAt));
                ListUtil.reverse(fulfillmentEventList);
                ShopifyFulfillmentEvent shopifyFulfillmentEvent = fulfillmentEventList.get(0);
                String formatStr = String.format("%s -> %s", shopifyFulfillmentEvent.getHappenedAt(), shopifyFulfillmentEvent.getMessage());
                shopifyOrderVoItem.setLastTrackStr(formatStr);
            }
        }

        return shopifyOrderVoItemList;
    }

}
